package org.seamon.management.util;

import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Simon
 */
@Component
@AllArgsConstructor
public class RedissonUtil {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取锁
     *
     * @param key 锁的 key
     * @return 锁
     */
    public RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

    /**
     * 设置 key-value 并设置过期时间（使用 Duration）
     *
     * @param key      键
     * @param value    值
     * @param duration 过期时间（Duration 类型）
     */
    public void setWithExpire(String key, Object value, Duration duration) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value, duration);
    }

    /**
     * 获取 key 对应的值
     */
    public Object get(String key) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 判断 key 是否存在
     */
    public boolean exists(String key) {
        return redissonClient.getBucket(key).isExists();
    }

    /**
     * 删除某个 key
     */
    public void delete(String key) {
        redissonClient.getBucket(key).delete();
    }

    /**
     * 获取剩余过期时间（返回 Duration）
     */
    public Duration getExpire(String key) {
        return Duration.ofNanos(redissonClient.getBucket(key).remainTimeToLive());
    }
}
